/* main.c */

#include "app_inc.h"

static void LowPower_EnterDeepSleep(bool enSleepOnExit);

int main(void)
{   
    /* Initialize the board. */
    BSP_InitSystem();
    BSP_InitStdioUART(115200);
    
    printf("\r\nHello, World\r\n");
    
    /* Configure the LED. */
    PORTE->PCR[6] = PORT_PCR_MUX(1);
    GPIO_SetPinDir(PTE, 6U, true);
    GPIO_SetPinLogic(PTE, 6U, true);
    
    /* Configure the Button. */
    /* PTA4, PORT interrupt, not using LLWU. */
    PORTA->PCR[4] = PORT_PCR_ISF_MASK    /* Clear event flag. */
                    | PORT_PCR_IRQC(0xA) /* Interrupt on falling-edge. */
                    | PORT_PCR_PE_MASK
                    | PORT_PCR_PS_MASK
                    | PORT_PCR_MUX(1); /* GPIO/LLWU. */
    NVIC_EnableIRQ(PORTA_IRQn);
    
    printf("Ready to fall into STOP mode.\r\n");

    LowPower_EnterDeepSleep(false);
    
    while (1)
    {
        printf("Waken up!\r\n");
        __ASM("WFI");
    }
}

static void LowPower_EnterDeepSleep(bool enSleepOnExit)
{
    /* Set the SLEEPDEEP bit to enable deep sleep mode (STOP) */
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    if (enSleepOnExit)
    {
        SCB->SCR |= SCB_SCR_SLEEPONEXIT_Msk;
    }
    else
    {
        SCB->SCR &= ~SCB_SCR_SLEEPONEXIT_Msk;
    }
    /* WFI instruction will start entry into STOP mode */
    __ASM("WFI");
}

void PORTA_IRQHandler(void)
{
    NVIC_DisableIRQ(PORTA_IRQn); /* Disable the interrupt to avoid interrupt nest. */

    PORTA->ISFR = 0xFFFFFFFF; /* Clear int flag. */
    GPIO_TogglePinLogic(PTE, 6U); /* Toggle the LED. */
    
    NVIC_EnableIRQ(PORTA_IRQn);
}

/* EOF. */

